package com.woniuxy.yygh.msm.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.woniuxy.yygh.msm.service.FileService;
import com.woniuxy.yygh.msm.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO:文件上传实现
 * <P> Date: 2022/3/4:20:48
 * <P> Description:
 */
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。

        String endpoint = ConstantOssPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;

        try {
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            //获得文件名字
            String fileName = file.getOriginalFilename();

            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //按照当前日期，创建文件夹，上传到创建文件夹里面 会自动创建文件夹
            // 2022/3/4/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;

            //调用方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient
            ossClient.shutdown();

            //上传之后文件路径
            //https://yygh-myyygh.oss-cn-beijing.aliyuncs.com/2022/03/04//01.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            //返回url地址
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

